<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="品牌名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入品牌名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="品牌积分" prop="integral">
        <el-input
          v-model="queryParams.integral"
          placeholder="请输入品牌积分"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="品牌图片" prop="images">
        <el-input
          v-model="queryParams.images"
          placeholder="请输入品牌图片"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['membershipcard:membershipcard:add']"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['membershipcard:membershipcard:edit']"
        >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['membershipcard:membershipcard:remove']"
        >删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['membershipcard:membershipcard:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="membershipcardList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="id" align="center" prop="id" /> -->
      <el-table-column label="序号" type="index" :index="(queryParams.pageNum-1)*10+1" />
      <el-table-column label="品牌名称" align="center" prop="name" />
      <el-table-column label="品牌积分" align="center" prop="integral" />
      <!-- <el-table-column label="品牌图片" align="center" prop="images" /> -->
      <el-table-column label="品牌图片" align="center">
          <template slot-scope="scope">
            <el-image
              style="width: 50px; height: 50px"
              :src="scope.row.images"
              fit="cover"
            ></el-image>
          </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.switchOpen == 1" effect="dark" type="success">已开启</el-tag>
            <el-tag v-else effect="dark" type="danger">已关闭</el-tag>
          </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="修改人" align="center" prop="updateBy" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['membershipcard:membershipcard:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-link"
            @click="getGoods(scope.row)"
            v-hasPermi="['member:member:edit']"
          >绑定礼品</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['membershipcard:membershipcard:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改品牌会员卡对话框 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- <el-form-item label="逻辑删除" prop="isDelete">
          <el-input v-model="form.isDelete" placeholder="请输入逻辑删除" />
        </el-form-item> -->
        <el-form-item label="品牌名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入品牌名称" />
        </el-form-item>
        <el-form-item label="品牌积分" prop="integral">
          <el-input v-model="form.integral" placeholder="请输入品牌积分"   @input="form.integral = form.integral.replace(/[^\.\d]/g,'')"/>
        </el-form-item>
        
        <el-form-item label="品牌图片" prop="images" :class="form.images?'upHide':''">
          <el-upload
            ref="upload"
            :action="$uploadImage"
            list-type="picture-card"
            :on-success="uploadSuccess"
            :on-remove="removeImage"
            :file-list="imageList"
            :headers="headers"
            name="fileList"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio v-model="form.switchOpen" :label="1" size="large">开启</el-radio>
          <el-radio v-model="form.switchOpen" :label="0" size="large">关闭</el-radio>
        </el-form-item>
      </el-form>
      
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" title="绑定礼品" v-loading="loading" :visible.sync="showGoods" width="80vw" append-to-body>
      <el-checkbox-group v-model="brandgiftsIdList">
        <el-checkbox v-for="(item,index) in brandgiftsList" :key="index" :label="item.id">
          <div class="cardBox">
            <div class="cardName">{{item.giftName}}</div>
            <el-image
              style="width: 100px; height: 100px"
              :src="item.giftImages"
              fit="cover"
            ></el-image>
          </div>
        </el-checkbox>
      </el-checkbox-group>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="bindingGoods">确 定</el-button>
        <el-button @click="showGoods = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { binding,getBindingGoods,listMembershipcard, getMembershipcard, delMembershipcard, addMembershipcard, updateMembershipcard, exportMembershipcard } from "@/api/membershipcard/membershipcard";
import { listBrandgifts } from "@/api/brandgifts/brandgifts";
import { getToken } from '@/utils/auth'
export default {
  name: "Membershipcard",
  components: {
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      imageList:[],
      // 品牌会员卡表格数据
      membershipcardList: [],
      brandgiftsList:[], // 品牌商品列表
      brandgiftsIdList:[], // 品牌商品id列表
      showGoods:false,//显示商品列表
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        integral: null,
        images: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name:[
          {required:true,message:'请填写品牌名称',trigger: 'change'}
        ],
        integral:[
          {required:true,message:'请填写品牌积分',trigger: 'change'}
        ],
        images:[
          {required:true,message:'请选择品牌图片',trigger: 'change'}
        ]
      }
    };
  },
  computed:{
    headers(){
      return {
        'Authorization':'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
      }
    }
  },
  created() {
    this.getList();
  },
  methods: {
    // 删除图片
    removeImage(){
      this.form.images = ""
    },
    // 上传成功
    uploadSuccess(e){
      console.log(e,'上传成功')
      this.$set(this.form,'images',e.data[0])
      this.$refs.form.validateField(['images'])
    },
    // 绑定礼品
    bindingGoods(){
      this.loading = true;
      binding({id:this.form.id,cardIds:this.brandgiftsIdList}).then(response => {
        this.msgSuccess("修改成功");
        this.loading = false;
        this.showGoods = false;
        this.getList();
      })
      .catch(()=>{
        this.loading = false;
      })
    },
    // 获取绑定礼品
    getGoods(row){
      this.loading = true
      this.form = row
      getBindingGoods(row.id).then(response=>{
        this.showGoods = true
        console.log(response)
        let arr = []
        if(response.data&&response.data.ttBrandGiftsList){
          arr = response.data.ttBrandGiftsList
        }
        this.brandgiftsIdList = arr.map(item=>{
          return item.id+''
        })
        this.getGoodsList();
      }).catch((e)=>{
        console.log(e)
        this.loading = false;
      })
    },
    // 获取品牌商品列表
    getGoodsList() {
      this.loading = true;
      listBrandgifts({
        pageNum: 1,
        pageSize: 10000
      }).then(response => {
        this.brandgiftsList = response.rows.map(item=>{
          item.id = item.id+''
          return item
        });
        this.loading = false;
      }).catch(()=>{
        this.loading = false;
      })
    },
    /** 查询品牌会员卡列表 */
    getList() {
      this.loading = true;
      listMembershipcard(this.queryParams).then(response => {
        this.membershipcardList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        isDelete: null,
        name: null,
        switchOpen:1,
        integral: null,
        images: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加品牌会员卡";
      this.imageList = []
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getMembershipcard(id).then(response => {
        this.form = response.data;
        this.imageList = [{
          name:'图片',
          url:response.data.images
        }]
        this.open = true;
        this.title = "修改品牌会员卡";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateMembershipcard(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMembershipcard(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除品牌会员卡编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delMembershipcard(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有品牌会员卡数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportMembershipcard(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    }
  }
};
</script>
<style>
.upHide .el-upload{
  display: none;
}
</style>
<style scoped>
.cardCheckBox{
  align-items: flex-start;
}
.cardName{
  width: 100px;
  line-height: 20px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
</style>
